package com.lst.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lst.api.constant.RedisKeysConstant;
import com.lst.api.entity.AddressProvince;
import com.lst.api.mapper.AddressProvinceMapper;
import com.lst.api.service.IAddressProvinceService;
import com.lst.tools.mybatis.constant.StatusConstants;
import com.lst.tools.mybatis.service.impl.BaseService;
import com.lst.tools.mybatis.utils.ExpandSqlUtils;
import com.lst.tools.redis.service.IRedisService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 省份表业务层实现
 *
 * @author Frank
 * @date 2019-09-29 14:14:26
 * @version: V1.0
 */
@Service
public class AddressProvinceService extends BaseService<AddressProvinceMapper, AddressProvince> implements IAddressProvinceService {

    @Autowired
    private IRedisService redisService;

    @Override
    public List<AddressProvince> listAll() {
        QueryWrapper<AddressProvince> queryWrapper = new QueryWrapper();
        queryWrapper.eq(AddressProvince.IS_DELETE, StatusConstants.IS_NOT_DELETE);
        queryWrapper
                .orderByAsc(ExpandSqlUtils.getIsNullOrderBy(AddressProvince.SORT, false))
                .orderByAsc(AddressProvince.SORT)
                .orderByDesc(AddressProvince.CREATE_AT)
                .orderByDesc(AddressProvince.ID);
        return super.list(queryWrapper);
    }

    @Override
    public Map<String, String> getAllCodeMap() {
        String dataJson = redisService.hGet(RedisKeysConstant.ADDRESS, RedisKeysConstant.ADDRESS_PROVINCE_MAP);
        if (StringUtils.isNotBlank(dataJson)) {
            return JSON.parseObject(dataJson, new TypeReference<Map<String, String>>() {
            });
        }
        Map<String, AddressProvince> allMap = super.getObjectMapByStringField(AddressProvince.CODE, null);
        if (MapUtils.isEmpty(allMap)) {
            return Collections.emptyMap();
        }
        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, AddressProvince> entry : allMap.entrySet()) {
            map.put(entry.getKey(), entry.getValue().getShortName());
        }
        redisService.hSet(RedisKeysConstant.ADDRESS, RedisKeysConstant.ADDRESS_PROVINCE_MAP, JSON.toJSONString(map));
        return map;
    }
}